import axios from 'axios';
var qs = require('qs');
import {
  Message
} from "element-ui";

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.API_URL,
  timeout: 5000,
  headers: {
    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
  },
});

// 拦截请求
service.interceptors.request.use(function (config) {
  const token = localStorage.getItem('token');
  const username = localStorage.getItem('username');
  if (!config.data) {
    config.data = {};
  }
  // 判断请求类型
  if (config.method === 'post') {
    // let data = qs.parse(config.data);
    // config.data = qs.stringify({
    //   userName:username,
    //   accessToken:token,
    //   ...data,
    // });
    config.data.userName = username;
    config.data.accessToken = token;
    config.headers = {
      "Content-Type": "application/json;charset=utf-8"
    };
  }
  if (config.method === 'get') {
    config.params = config.data;
    config.params.userName = username;
    config.params.accessToken = token;
    config.headers = {
      "Content-Type": "text/plain;charset=utf-8"
    };
  }
  if (config.url == 'login') {
    let data = qs.parse(config.data);
    config.data = qs.stringify({
      userName: username,
      accessToken: token,
      ...data,
    });
    config.headers = {
      "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
    };
  }
  if (config.url != 'login') {
    config.headers.accessToken = localStorage.getItem('token');
  }
  // }
  return config;
}, function (error) {
  return Promise.reject(error);
})

// 拦截响应
service.interceptors.response.use(function (response) {
  if(response['data']['result'] == null) {
    response['data']['code'] = "401";
  }
  if (response['data']['msg'] == "您没有权限访问该页面") {
    Message({
      showClose: true,
      message: "登陆已过期，请重新登陆",
      type: "warning"
    });
  } else if (response['data']['msg'] == "failure") {
    Message({
      showClose: true,
      message: "服务器出错了，请联系管理员",
      type: "error"
    });
  } else if (response['data']['code'] == "403") {
    Message({
      showClose: true,
      message: "您没有权限",
      type: "error"
    });
  } else if (response['data']['code'] == "500") {
    Message({
      showClose: true,
      message: "服务器错误",
      type: "error"
    });
  }
  return response;
}, error => {
  // Message({
  //   showClose: true,
  //   message: "服务器出了个小差，请稍后重试",
  //   type: "error"
  // });
  // return Promise.reject(error);
  let response ={data:{code:""}};
  response['data']['code'] ='201';
  return response;
})

export default service;
